package com.letianpai.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.widget.GridView;
import android.widget.Toast;

import com.letianpai.bean.UserContacts;

public class ContactsUtils {
    /*
     * 获取联系人
     */
    public static List<UserContacts>getContacts(Context context) {
        List<UserContacts> callList = new ArrayList<UserContacts>();
        ContentResolver cr = context.getContentResolver();
        final String[] PHONES_PROJECTION = new String[] { Phone.DISPLAY_NAME,
                Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
        Cursor phoneCursor = cr.query(Phone.CONTENT_URI, PHONES_PROJECTION,
                null, null, null);

        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()){
                UserContacts us = new UserContacts();
                ArrayList<String> number = new ArrayList<String>();
                // 得到手机号码
                String phoneNumber = phoneCursor.getString(1);
                if(phoneNumber.contains("+86")){
                    phoneNumber=phoneNumber.substring(3, phoneNumber.length());
                }
                // 当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                // 得到联系人名称
                String contactName = phoneCursor.getString(0);
                // 得到联系人ID

                Long photoid = phoneCursor.getLong(2);
                Long contactid = phoneCursor.getLong(3);
                us.setName(contactName);
                number.add(phoneNumber);
                us.setUserId(contactid + "");
                us.setNumber(number);

                us.setPlace(ContactsUtils.queryplace(context, phoneNumber));
				/*
				 * if (null != contactName) { Uri uri = Uri
				 * .parse("content://com.android.contacts/data/phones/filter/" +
				 * contactName); Cursor cursor2 = cr.query(uri, new String[]
				 * {"photo_id"}, null, null, null);
				 */

                if (photoid > 0) {

					/*
					 * String phot_ID = cursor2.getString(0); if (null !=
					 * phot_ID) {
					 */
                    Cursor cursor3 = cr.query(
                            ContactsContract.Data.CONTENT_URI,
                            new String[] { "data15" },
                            "ContactsContract.Data._ID=" + photoid, null, null);
                    us.setPictureId(photoid + "");
                    if (cursor3.moveToFirst()) {
                        byte[] photoicon = cursor3.getBlob(0);

                        ByteArrayInputStream inputStream = new ByteArrayInputStream(
                                photoicon);

                        Bitmap contactPhoto = BitmapFactory
                                .decodeStream(inputStream);
                        us.setPicture(contactPhoto);
                    }
                    cursor3.close();

                }


                callList.add(us);
            }
        }
        phoneCursor.close();
        //not reat arraylist!!!
        for (int i = 0; i < callList.size()-1; i++)
        {
            for (int j = i + 1; j < callList.size(); j++)
            {
                if (callList.get(i).getName().equals(callList.get(j).getName()))
                {
                    callList.remove(j);
                    j--;
                }
            }
        }

        return callList;
    }

    /*
     * 获取联系人姓名
     */
    public static List<UserContacts> getName(Context context) {

        List<UserContacts> callList = new ArrayList<UserContacts>();
        ContentResolver cr = context.getContentResolver();
        final String[] PHONES_PROJECTION = new String[] { Phone.DISPLAY_NAME,
                Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
        Cursor phoneCursor = cr.query(Phone.CONTENT_URI, PHONES_PROJECTION,
                null, null, null);

        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                UserContacts us = new UserContacts();
                ArrayList<String> number = new ArrayList<String>();
                // 得到手机号码
                String phoneNumber = phoneCursor.getString(1);
                // 当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                // 得到联系人名称
                String contactName = phoneCursor.getString(0);
                Long contactid = phoneCursor.getLong(3);
                us.setUserId(contactid + "");
                us.setName(contactName);
                number.add(phoneNumber);
                us.setNumber(number);
                callList.add(us);
            }
        }
        phoneCursor.close();

        return callList;

    }

    /*
     * 获取一个联系人所有信息by ID
     */
    public static UserContacts getOneContacts(Context context, String id) {
        UserContacts uc = new UserContacts();

        uc.setUserId(id);
        // 获得联系人的电话号码
        Cursor phones = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                null, null);
        ArrayList<String> number = new ArrayList<String>();
        if (phones.moveToFirst()) {
            do {
                // 遍历所有的电话号码
                String phoneNumber = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                number.add(phoneNumber);
                String phoneType = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
            } while (phones.moveToNext());
        }
        uc.setNumber(number);

        phones.close();

        // 获取该联系人邮箱
        ArrayList<String> emailList = new ArrayList<String>();
        Cursor emails = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                null, null);
        if (emails.moveToFirst()) {
            do {
                // 遍历所有的电话号码
                String emailType = emails
                        .getString(emails
                                .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

                String emailValue = emails
                        .getString(emails
                                .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                emailList.add(emailValue);

            } while (emails.moveToNext());
        }
        emails.close();
        if (emailList.size() > 0) {
            uc.setHaveEmail(true);
        }
        uc.setEmail(emailList);
        // 获取该联系人IM
        ArrayList<String> IMList = new ArrayList<String>();
        Cursor IMs = context.getContentResolver()
                .query(Data.CONTENT_URI,
                        new String[] { Data._ID, Im.PROTOCOL, Im.DATA },
                        Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
                                + Im.CONTENT_ITEM_TYPE + "'",
                        new String[] { id }, null);
        if (IMs.moveToFirst()) {
            do {
                String protocol = IMs
                        .getString(IMs.getColumnIndex(Im.PROTOCOL));
                String date = IMs.getString(IMs.getColumnIndex(Im.DATA));
                IMList.add(date);

            } while (IMs.moveToNext());
        }
        IMs.close();
        if (IMList.size() > 0) {
            uc.setHaveIm(true);
        }
        uc.setUserIM(IMList);
        // 获取该联系人地址
        ArrayList<String> addressList = new ArrayList<String>();
        Cursor address = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                null, null);
        if (address.moveToFirst()) {
            do {
                // 遍历所有的地址
                String street = address
                        .getString(address
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
                String city = address
                        .getString(address
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                String region = address
                        .getString(address
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
                String postCode = address
                        .getString(address
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
                String formatAddress = address
                        .getString(address
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
                addressList.add(formatAddress);
            } while (address.moveToNext());
        }
        address.close();
        if (addressList.size() > 0) {
            uc.setHaveAddress(true);
        }
        uc.setAddress(addressList);
        // 获取该联系人组织
        Cursor organizations = context.getContentResolver().query(
                Data.CONTENT_URI,
                new String[] { Data._ID, Organization.COMPANY,
                        Organization.TITLE },
                Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
                        + Organization.CONTENT_ITEM_TYPE + "'",
                new String[] { id }, null);
        if (organizations.moveToFirst()) {
            do {
                String company = organizations.getString(organizations
                        .getColumnIndex(Organization.COMPANY));
                String title = organizations.getString(organizations
                        .getColumnIndex(Organization.TITLE));
            } while (organizations.moveToNext());
        }
        organizations.close();
        // 获取备注信息
        ArrayList<String> notesList = new ArrayList<String>();
        Cursor notes = context.getContentResolver().query(
                Data.CONTENT_URI,
                new String[] { Data._ID, Note.NOTE },
                Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
                        + Note.CONTENT_ITEM_TYPE + "'", new String[] { id },
                null);
        if (notes.moveToFirst()) {
            do {
                String noteinfo = notes.getString(notes
                        .getColumnIndex(Note.NOTE));
                notesList.add(noteinfo);
            } while (notes.moveToNext());
        }
        uc.setRemarks(notesList);
        if (notesList.size() > 0) {
            uc.setHaveRemarks(true);
        }
        notes.close();

        // 获取nickname信息
        ArrayList<String> nickName = new ArrayList<String>();
        Cursor nicknames = context.getContentResolver().query(
                Data.CONTENT_URI,
                new String[] { Data._ID, Nickname.NAME },
                Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
                        + Nickname.CONTENT_ITEM_TYPE + "'",
                new String[] { id }, null);
        if (nicknames.moveToFirst()) {
            do {
                String nickname_ = nicknames.getString(nicknames
                        .getColumnIndex(Nickname.NAME));
                nickName.add(nickname_);
            } while (nicknames.moveToNext());
        }
        nicknames.close();
        if (nickName.size() > 0) {
            uc.setHaveNickName(true);
        }
        uc.setNickName(nickName);
        return uc;
    }

    /*
     * 获取联系人的信息
     */
    public static List<String> getUserInformation(UserContacts uc) {
        List<String> userInformation = new ArrayList<String>();
		/*
		 * 获取联系人的信息
		 */
        if (uc.getNumber() != null&&uc.getNumber().size()>1) {
            for (int i = 1; i < uc.getNumber().size(); i++) {
                userInformation.add(uc.getNumber().get(i));
            }
        }
        if (uc.getAddress() != null) {
            for (int i = 0; i < uc.getAddress().size(); i++) {
                userInformation.add(uc.getAddress().get(i));
            }
        }
        if (uc.getEmail() != null) {
            for (int i = 0; i < uc.getEmail().size(); i++) {
                userInformation.add(uc.getEmail().get(i));
            }
        }
        if (uc.getRemarks() != null) {
            for (int i = 0; i < uc.getRemarks().size(); i++) {
                userInformation.add(uc.getRemarks().get(i));
            }
        }
        if (uc.getUserIM() != null) {
            for (int i = 0; i < uc.getUserIM().size(); i++) {
                userInformation.add(uc.getUserIM().get(i));
            }
        }
        if (uc.getNickName() != null) {
            for (int i = 0; i < uc.getNickName().size(); i++) {
                userInformation.add(uc.getNickName().get(i));
            }
        }
        return userInformation;
    }

    /*
     * 获取联系人的信息名称
     */
    public static List<String> getContactsName(UserContacts uc) {
        List<String> contactsName = new ArrayList<String>();
        if (uc.getNumber() != null&&uc.getNumber().size()>1) {
            for (int i = 0; i < uc.getNumber().size(); i++) {
                contactsName.add("电话");
            }
        }
        if (uc.getAddress() != null) {
            for (int i = 0; i < uc.getAddress().size(); i++) {
                contactsName.add("地址");
            }
        }
        if (uc.getEmail() != null) {
            for (int i = 0; i < uc.getEmail().size(); i++) {
                contactsName.add("邮箱");
            }
        }
        if (uc.getRemarks() != null) {
            for (int i = 0; i < uc.getRemarks().size(); i++) {
                contactsName.add("备注");
            }
        }
        if (uc.getUserIM() != null) {
            for (int i = 0; i < uc.getUserIM().size(); i++) {
                contactsName.add("IM");
            }
        }
        if (uc.getNickName() != null) {
            for (int i = 0; i < uc.getNickName().size(); i++) {
                contactsName.add("昵称");
            }
        }

        return contactsName;
    }

    /*
     * 插入联系人
     */
    public static void insert(Context context, UserContacts user) {
        // 首先插入空值，再得到rawContactsId ，用于下面插值
        ContentValues values = new ContentValues();
        // insert a null value
        Uri rawContactUri = context.getContentResolver().insert(
                RawContacts.CONTENT_URI, values);
        long rawContactsId = ContentUris.parseId(rawContactUri);

        // 往刚才的空记录中插入姓名
        values.clear();
        values.put(StructuredName.RAW_CONTACT_ID, rawContactsId);

        // "CONTENT_ITEM_TYPE" MIME type used when storing this in data table
        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        // The name that should be used to display the contact.
        values.put(StructuredName.DISPLAY_NAME, user.getName());
        // insert the real values
        context.getContentResolver().insert(Data.CONTENT_URI, values);

        // 插入电话
        values.clear();

        values.put(Phone.RAW_CONTACT_ID, rawContactsId);
        // String "Data.MIMETYPE":The MIME type of the item represented by this
        // row
        // String "CONTENT_ITEM_TYPE": MIME type used when storing this in data
        // table.
        values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
        // for (int i = 0; i < user.getNumber().size(); i++) {
        if (user.getNumber().size() > 0) {
            values.put(Phone.NUMBER, user.getNumber().get(0));
            context.getContentResolver().insert(Data.CONTENT_URI, values);

        }

        // }

        // 插入邮箱
        values.clear();
        values.put("raw_contact_id", rawContactsId);
        values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
        // for (int i = 0; i < user.getEmail().size(); i++) {
        if (user.getEmail().size() > 0) {
            values.put(Email.DATA, user.getEmail().get(0));
            values.put(Email.TYPE, Email.TYPE_WORK);
            context.getContentResolver().insert(Data.CONTENT_URI, values);

        }

        // }

        // 插入地址
        values.clear();
        values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
        // for (int i = 0; i < user.getAddress().size(); i++) {
		/*
		 * if (user.getAddress().size() > 0) {
		 *
		 * values.put(StructuredPostal.FORMATTED_ADDRESS, user.getAddress()
		 * .get(0)); values.put(StructuredPostal.TYPE,
		 * StructuredPostal.TYPE_WORK);
		 * context.getContentResolver().insert(Data.CONTENT_URI, values); }
		 */
        // }

        // 添加头像
		/*
		 * values.clear(); Bitmap sourceBitmap =
		 * CallUtils.getBitmap(user.getPictureId(), context); final
		 * ByteArrayOutputStream os = new ByteArrayOutputStream(); //
		 * 将Bitmap压缩成PNG编码，质量为100%存储
		 * sourceBitmap.compress(Bitmap.CompressFormat.PNG, 100, os); byte[]
		 * avatar = os.toByteArray(); values.put(Data.MIMETYPE,
		 * Photo.CONTENT_ITEM_TYPE); values.put(Photo.PHOTO, avatar);
		 * context.getContentResolver().insert(Data.CONTENT_URI, values);
		 */
        Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();
    }

    // 查询归属地
    public static String queryplace(Context context, String phoneNumber) {
        phoneNumber = phoneNumber.replaceAll(" ", "");

        SQLiteDatabase sqliteDB;
        DatabaseDAO dao;

        AssetsDatabaseManager.initManager(context);
        AssetsDatabaseManager mg = AssetsDatabaseManager
                .getAssetsDatabaseManager();

        sqliteDB = mg.getDatabase("number_location.zip");
        dao = new DatabaseDAO(sqliteDB);

        String prefix, center;
        Map<String, String> map = null;

        if (isZeroStarted(phoneNumber) && getNumLength(phoneNumber) > 2) {
            prefix = getAreaCodePrefix(phoneNumber);
            map = dao.queryAeraCode(prefix);
            String province = map.get("province");
            String city = map.get("city");
            if (province != null && city != null && province.equals(city)) {
                return province;
            }
            if (province == null) {
                return "未知";
            }
            return province + "" + city;
        } else if (!isZeroStarted(phoneNumber) && getNumLength(phoneNumber) > 6) {
            prefix = getMobilePrefix(phoneNumber);
            center = getCenterNumber(phoneNumber);
            map = dao.queryNumber(prefix, center);
            String province = map.get("province");
            String city = map.get("city");

            if (province != null && city != null && province.equals(city)) {
                return province;
            }
            if (province == null) {
                return "未知";
            }

            return province + "" + city;

        }
        return "未知";
    }

    public static String getAreaCodePrefix(String number) {
        if (number.charAt(1) == '1' || number.charAt(1) == '2')
            return number.substring(1, 3);
        return number.substring(1, 4);
    }

    public static String getMobilePrefix(String number) {
        return number.substring(0, 3);
    }

    public static String getCenterNumber(String number) {
        return number.substring(3, 7);
    }

    public static boolean isZeroStarted(String number) {
        if (number == null || number.isEmpty()) {
            return false;
        }
        return number.charAt(0) == '0';
    }

    public static int getNumLength(String number) {
        if (number == null || number.isEmpty())
            return 0;
        return number.length();
    }

	/*
	 * 测试
	 */

    public static void addContact(Context context, UserContacts uc) {

        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        // 在名片表插入一个新名片
        ops.add(ContentProviderOperation
                .newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                .withValue(ContactsContract.RawContacts._ID, 0)
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                .withValue(ContactsContract.RawContacts.AGGREGATION_MODE,
                        ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED)
                .build());

        // add name
        // 添加一条新名字记录；对应RAW_CONTACT_ID为0的名片
        if (!uc.getName().equals("")) {
            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                            uc.getName()).build());
        }

        // 添加昵称

        ops.add(ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(
                        ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Nickname.NAME,
                        "Anson昵称").build());

        // add company
		/*
		 * if (!organisation.equals("")) {
		 * ops.add(ContentProviderOperation.newInsert
		 * (ContactsContract.Data.CONTENT_URI
		 * ).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
		 * 0).withValue(ContactsContract.Data.MIMETYPE,
		 * ContactsContract.CommonDataKinds
		 * .Organization.CONTENT_ITEM_TYPE).withValue(
		 * ContactsContract.CommonDataKinds
		 * .Organization.COMPANY,organisation).withValue(
		 * ContactsContract.CommonDataKinds
		 * .Organization.TYPE,ContactsContract.CommonDataKinds
		 * .Organization.TYPE_WORK).build()); }
		 */

        // add phone
        for (int i = 0; i < uc.getNumber().size(); i++) {

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,
                            uc.getNumber().get(i))
                    .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 1)
                    .build());
        }

        // add Fax
		/*
		 * if (!fax.equals("")) {
		 * ops.add(ContentProviderOperation.newInsert(ContactsContract
		 * .Data.CONTENT_URI).withValueBackReference(
		 * ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(
		 * ContactsContract.Data.MIMETYPE,
		 * ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(
		 * ContactsContract.CommonDataKinds.Phone.NUMBER,fax)
		 * .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
		 * ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK).build()); }
		 */

        // add email
        for (int i = 0; i < uc.getEmail().size(); i++) {

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Email.DATA,
                            uc.getEmail().get(i))
                    .withValue(ContactsContract.CommonDataKinds.Email.TYPE, 1)
                    .build());
        }

        // add address
        for (int i = 0; i < uc.getAddress().size(); i++) {

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                            uc.getAddress().get(i))
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)
                    .build());
        }

        // add website
		/*
		 * if (!website.equals("")) {
		 * ops.add(ContentProviderOperation.newInsert(
		 * ContactsContract.Data.CONTENT_URI)
		 * .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
		 * .withValue(ContactsContract.Data.MIMETYPE,
		 * ContactsContract.CommonDataKinds
		 * .Website.CONTENT_ITEM_TYPE).withValue(
		 * ContactsContract.CommonDataKinds.Website.URL,website) .withValue(
		 * ContactsContract.CommonDataKinds.Website.TYPE,
		 * ContactsContract.CommonDataKinds.Website.TYPE_WORK).build()); }
		 */

        // add IM
        for (int i = 0; i < uc.getUserIM().size(); i++) {

            ops.add(ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Im.DATA1,
                            uc.getUserIM().get(i))
                    .withValue(ContactsContract.CommonDataKinds.Im.PROTOCOL,
                            ContactsContract.CommonDataKinds.Im.PROTOCOL_QQ)
                    .build());
        }

		/*
		 * Bitmap bm = uc.getPicture(); if (bm != null) { ByteArrayOutputStream
		 * baos = new ByteArrayOutputStream();
		 * bm.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] photo =
		 * baos.toByteArray(); if (photo != null) {
		 *
		 * ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.
		 * CONTENT_URI)
		 * .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
		 * .withValue(ContactsContract.Data.MIMETYPE,
		 * ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
		 * .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo)
		 * .build()); } }
		 */

        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
                    ops);
        } catch (Exception e) {
        }
        Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();
    }

    /*
     * 根据电话号码查询联系人id
     */
    public static String getContactId(Context context, String number) {

        Cursor c = null;

        try {

            c = context.getContentResolver().query(Phone.CONTENT_URI,

                    new String[] { Phone.CONTACT_ID, Phone.NUMBER }, null, null, null);

            if (c != null && c.moveToFirst()) {

                while (!c.isAfterLast()) {

                    if (PhoneNumberUtils.compare(number, c.getString(1))) {

                        return c.getString(0);

                    }

                    c.moveToNext();

                }

            }

        } catch (Exception e) {

        } finally {

            if (c != null) {
                c.close();

            }

        }

        return null;

    }

    /*
     * 根据号码查询姓名图片
     */
    public static UserContacts getContactsInformation(Context context,
                                                      String number) {
        UserContacts uc = new UserContacts();
        String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER };
        String name = "";
        // 将自己添加到 msPeers 中
        Cursor cursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection, // Which columns to return.
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + number
                        + "'", // WHERE clause.
                null, // WHERE clause value substitution
                null); // Sort order.

        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);

            // 取得联系人名字
            int nameFieldColumnIndex = cursor
                    .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            name = cursor.getString(nameFieldColumnIndex);
            uc.setName(name);
        }
        if (null != name) {
            Uri uri = Uri
                    .parse("content://com.android.contacts/data/phones/filter/"
                            + name);
            Cursor cursor2 = context.getContentResolver().query(uri,
                    new String[] { "photo_id" }, null, null, null);

            if (cursor2.moveToFirst()) {

                String phot_ID = cursor2.getString(0);
                if (null != phot_ID) {
                    Cursor cursor3 = context.getContentResolver().query(
                            ContactsContract.Data.CONTENT_URI,
                            new String[] { "data15" },
                            "ContactsContract.Data._ID=" + phot_ID, null, null);
                    uc.setPictureId(phot_ID);
                    if (cursor3.moveToFirst()) {
                        byte[] photoicon = cursor3.getBlob(0);

                        ByteArrayInputStream inputStream = new ByteArrayInputStream(
                                photoicon);

                        Bitmap contactPhoto = BitmapFactory
                                .decodeStream(inputStream);
                        uc.setPicture(contactPhoto);
                    }
                    cursor3.close();

                }
            }

            cursor2.close();
        }
        return uc;
    }

    public static void toSaveContactInfo(Context context, UserContacts con) {
        ContentValues values = new ContentValues();
        // 首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获取系统返回的rawContactId
        Uri rawContactUri = context.getContentResolver().insert(
                RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);

        // 往data表入姓名数据
        values.clear();
        if (null != con.getName()) {
            values.put(Data.RAW_CONTACT_ID, rawContactId);
            values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
            values.put(StructuredName.GIVEN_NAME, con.getName());
            context.getContentResolver().insert(
                    android.provider.ContactsContract.Data.CONTENT_URI, values);
        }
        // 添加用户名 职位 部门
        // values.clear();TA
        // values.put(
        // android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
        // rawContactId);
        // values.put(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE);
        // values.put(Organization.LABEL, con.getName());
        // values.put(Organization.TITLE, con.getPlace());
        // values.put(Organization.COMPANY,con.getPlace());
        // values.put(Organization.TYPE, Organization.TYPE_WORK);
        // context.getContentResolver().insert(
        // android.provider.ContactsContract.Data.CONTENT_URI, values);
        // 添加邮箱
        values.clear();
        if (null != con.getEmail()) {
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
            for (int i = 0; i < con.getEmail().size(); i++) {
                values.put(Email.DATA, con.getEmail().get(i));
                values.put(Email.TYPE, Email.TYPE_WORK);
                context.getContentResolver().insert(
                        android.provider.ContactsContract.Data.CONTENT_URI,
                        values);
            }

        }
        // 添加手机

        values.clear();
        if (null != con.getNumber()) {
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
            for (int i = 0; i < con.getNumber().size(); i++) {
                values.put(Phone.NUMBER, con.getNumber().get(i));
                values.put(Phone.TYPE, Phone.TYPE_WORK_MOBILE);
                context.getContentResolver().insert(
                        android.provider.ContactsContract.Data.CONTENT_URI,
                        values);
            }

        }
        // }
        // 添加固定电话
		/*
		 * values.clear();
		 *
		 * values.put(
		 * android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
		 * rawContactId); values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
		 * values.put(Phone.NUMBER, con.getNumber().get(0));
		 * values.put(Phone.TYPE, Phone.TYPE_WORK);
		 * context.getContentResolver().insert(
		 * android.provider.ContactsContract.Data.CONTENT_URI, values);
		 */
        // 添加传真
        values.clear();
        // values.put(
        // android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
        // rawContactId);
        // values.put(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE);
        // values.put(Phone.NUMBER, con.getNumber().get(0));
        // values.put(Phone.TYPE, Phone.TYPE_FAX_WORK);
        // context.getContentResolver().insert(
        // android.provider.ContactsContract.Data.CONTENT_URI, values);
        // 添加 地址
        values.clear();
        if (null != con.getAddress()) {
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
            for (int i = 0; i < con.getAddress().size(); i++) {
                values.put(StructuredPostal.FORMATTED_ADDRESS, con.getAddress()
                        .get(i));
                values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK);
                context.getContentResolver().insert(
                        android.provider.ContactsContract.Data.CONTENT_URI,
                        values);
            }
        }

        // 添加头像
        values.clear();
        if (null != con.getHead()) {
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
            Bitmap image = drawableToBitmap(con.getHead());
            byte[] image2 = Bitmap2Bytes(image);
            values.put(Photo.PHOTO, image2);
            context.getContentResolver().insert(
                    android.provider.ContactsContract.Data.CONTENT_URI, values);
        }

        // 添加 IM
        values.clear();
        if (null != con.getUserIM()) {
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);
            for (int i = 0; i < con.getUserIM().size(); i++) {
                values.put(Im.DATA1, con.getUserIM().get(i));
                values.put(Im.PROTOCOL, Im.PROTOCOL_QQ);
                context.getContentResolver().insert(
                        android.provider.ContactsContract.Data.CONTENT_URI,
                        values);
            }
        }

        // 添加 备注
        values.clear();
        if (null != con.getRemarks()) {
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(Note.MIMETYPE, Note.CONTENT_ITEM_TYPE);
            for (int i = 0; i < con.getRemarks().size(); i++) {
                values.put(Note.NOTE, con.getRemarks().get(i));
                context.getContentResolver().insert(
                        android.provider.ContactsContract.Data.CONTENT_URI,
                        values);
            }
        }

        // 添加 昵称
        values.clear();
        if (null != con.getNickName()) {
            values.put(
                    android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                    rawContactId);
            values.put(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE);
            for (int i = 0; i < con.getNickName().size(); i++) {
                values.put(Nickname.NAME, con.getNickName().get(i));
                context.getContentResolver().insert(
                        android.provider.ContactsContract.Data.CONTENT_URI,
                        values);
            }
        }

        Toast.makeText(context, "已保存" + con.getName() + "的联系信息至本地通讯录",
                Toast.LENGTH_SHORT).show();
    }

    public static byte[] Bitmap2Bytes(Bitmap bm) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();

    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;

    }

    // 根据拼音首字母选择
    public static void letterSelected(List<String> newlist1, GridView gv,
                                      String letter) {
        for (int i = 0; i < newlist1.size(); i++) {
            if (newlist1.get(i).equals(letter)) {
                gv.setSelection(i);
                Log.d("zzzz", letter);
                break;
            }
        }
    }

    // 删除联系人
    public static void delContact(Context context, String name) {

        Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI,
                new String[] { Data.RAW_CONTACT_ID },

                ContactsContract.Contacts.DISPLAY_NAME + "=?",
                new String[] { name }, null);

        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        if (cursor.moveToFirst()) {
            do {
                long Id = cursor.getLong(cursor
                        .getColumnIndex(Data.RAW_CONTACT_ID));

                ops.add(ContentProviderOperation
                        .newDelete(
                                ContentUris.withAppendedId(
                                        RawContacts.CONTENT_URI, Id)).build());
                try {
                    context.getContentResolver().applyBatch(
                            ContactsContract.AUTHORITY, ops);
                } catch (Exception e) {
                }
            } while (cursor.moveToNext());
            cursor.close();
        }
    }

    public static void toupdateContact(Context context, String oldname,
                                       UserContacts user) {
        Toast.makeText(context, oldname+user.getName(), 1000).show();

        ContentValues values = new ContentValues();
        Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI,
                new String[] { Data.RAW_CONTACT_ID },
                ContactsContract.Contacts.DISPLAY_NAME + "=?",
                new String[] { oldname }, null);
        cursor.moveToFirst();
        String id = cursor
                .getString(cursor.getColumnIndex(Data.RAW_CONTACT_ID));
        cursor.close();
        ArrayList<ContentProviderOperation>ops=new ArrayList<ContentProviderOperation>();
        // 更新电话号码
        if (user.getNumber().size() != 0) {

            ops.add(ContentProviderOperation
                    .newUpdate(ContactsContract.Data.CONTENT_URI)
                    .withSelection(
                            Data.RAW_CONTACT_ID + "=?" + " AND "
                                    + ContactsContract.Data.MIMETYPE + " = ?"
                                    + " AND " + Phone.TYPE + "=?",
                            new String[] { String.valueOf(id),
                                    Phone.CONTENT_ITEM_TYPE,
                                    String.valueOf(Phone.TYPE_WORK_MOBILE) })
                    .withValue(Phone.NUMBER, user.getNumber().get(0)).build());
        }
        // }
        // 更新email

        if (user.getEmail().size() != 0) {
            if (user.isHaveEmail()) {
                ops.add(ContentProviderOperation
                        .newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                Data.RAW_CONTACT_ID + "=?" + " AND "
                                        + ContactsContract.Data.MIMETYPE
                                        + " = ?" + " AND " + Email.TYPE + "=?",
                                new String[] { String.valueOf(id),
                                        Email.CONTENT_ITEM_TYPE,
                                        String.valueOf(Email.TYPE_WORK) })
                        .withValue(Email.DATA, user.getEmail().get(0)).build());
            } else {
                values.put(
                        android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                        id);
                values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
                for (int i = 0; i < user.getEmail().size(); i++) {
                    values.put(Email.DATA, user.getEmail().get(i));
                    values.put(Email.TYPE, Email.TYPE_WORK);
                    context.getContentResolver().insert(
                            android.provider.ContactsContract.Data.CONTENT_URI,
                            values);
                }
            }

        }

        // 更新IM
        if (user.getUserIM().size() != 0) {
            if (user.isHaveIm()) {
                ops.add(ContentProviderOperation
                        .newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                Data.RAW_CONTACT_ID + "=?" + " AND "
                                        + ContactsContract.Data.MIMETYPE
                                        + " = ?" + " AND " + Im.PROTOCOL + "=?",
                                new String[] { String.valueOf(id),
                                        Im.CONTENT_ITEM_TYPE,
                                        String.valueOf(Im.PROTOCOL_QQ) })
                        .withValue(Im.DATA1, user.getUserIM().get(0)).build());
            } else {
                values.put(
                        android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                        id);
                values.put(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);
                for (int i = 0; i < user.getUserIM().size(); i++) {
                    values.put(Im.DATA1, user.getUserIM().get(i));
                    values.put(Im.PROTOCOL, Im.PROTOCOL_QQ);
                    context.getContentResolver().insert(
                            android.provider.ContactsContract.Data.CONTENT_URI,
                            values);
                }
            }
        }

        // 更新地址
        if (user.getAddress().size() != 0) {
            Toast.makeText(context, user.isHaveAddress()+"", 1000).show();
            if (user.isHaveAddress()) {
                ops.add(ContentProviderOperation
                        .newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                Data.RAW_CONTACT_ID + "=?" + " AND "
                                        + ContactsContract.Data.MIMETYPE
                                        + " = ?" + " AND "
                                        + StructuredPostal.TYPE + "=?",
                                new String[] {
                                        String.valueOf(id),
                                        StructuredPostal.CONTENT_ITEM_TYPE,
                                        String.valueOf(StructuredPostal.TYPE_WORK) })
                        .withValue(StructuredPostal.FORMATTED_ADDRESS,
                                user.getAddress().get(0)).build());
            } else {
                values.put(
                        android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                        id);
                values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
                for (int i = 0; i < user.getAddress().size(); i++) {
                    values.put(StructuredPostal.FORMATTED_ADDRESS, user
                            .getAddress().get(i));
                    values.put(StructuredPostal.TYPE,
                            StructuredPostal.TYPE_WORK);
                    context.getContentResolver().insert(
                            android.provider.ContactsContract.Data.CONTENT_URI,
                            values);
                }
            }
        }
		/*
		 * 更新网站
		 * ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.
		 * CONTENT_URI) .withSelection(Data.RAW_CONTACT_ID + "=?" + " AND "+
		 * ContactsContract.Data.MIMETYPE + " = ?",new String[] {
		 * String.valueOf(id),Website.CONTENT_ITEM_TYPE
		 * }).withValue(Website.URL, website).build()); // 更新公司
		 * ops.add(ContentProviderOperation
		 * .newUpdate(ContactsContract.Data.CONTENT_URI)
		 * .withSelection(Data.RAW_CONTACT_ID + "=?" + " AND "+
		 * ContactsContract.Data.MIMETYPE + " = ?",new String[] {
		 * String.valueOf(id),Organization.CONTENT_ITEM_TYPE })
		 * .withValue(Organization.COMPANY, organization).build());
		 */

        // 更新头像
        if (null != user.getHead()) {
            if (user.isHaveHead()) {
                Bitmap image = drawableToBitmap(user.getHead());
                byte[] image2 = Bitmap2Bytes(image);
                ops.add(ContentProviderOperation
                        .newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                Data.RAW_CONTACT_ID + "=?" + " AND "
                                        + Data.MIMETYPE + " = ?",
                                new String[] { String.valueOf(id),
                                        Photo.CONTENT_ITEM_TYPE })
                        .withValue(Photo.PHOTO, image2).build());

            } else {
                values.put(
                        android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                        id);
                values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
                Bitmap image = drawableToBitmap(user.getHead());
                byte[] image2 = Bitmap2Bytes(image);
                values.put(Photo.PHOTO, image2);
                context.getContentResolver().insert(
                        android.provider.ContactsContract.Data.CONTENT_URI,
                        values);
            }
        }
        // 更新姓名
        if (user.getName() != null) {
            ops.add(ContentProviderOperation
                    .newUpdate(ContactsContract.Data.CONTENT_URI)
                    .withSelection(
                            Data.RAW_CONTACT_ID + "=?" + " AND "
                                    + ContactsContract.Data.MIMETYPE + " = ?",
                            new String[] { String.valueOf(id),
                                    StructuredName.CONTENT_ITEM_TYPE })
                    .withValue(StructuredName.DISPLAY_NAME, user.getName())
                    .build());
        }
        // 更新备注
        if (user.getRemarks().size() != 0) {
            if(user.isHaveRemarks()){
                ops.add(ContentProviderOperation
                        .newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                Data.RAW_CONTACT_ID + "=?" + " AND "
                                        + ContactsContract.Data.MIMETYPE + " = ?",
                                new String[] { String.valueOf(id),
                                        Note.CONTENT_ITEM_TYPE })
                        .withValue(Note.NOTE, user.getRemarks().get(0)).build());
            }else{
                values.put(
                        android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                        id);
                values.put(Note.MIMETYPE, Note.CONTENT_ITEM_TYPE);
                for (int i = 0; i < user.getRemarks().size(); i++) {
                    values.put(Note.NOTE, user.getRemarks()
                            .get(i));
                    context.getContentResolver().insert(
                            android.provider.ContactsContract.Data.CONTENT_URI,
                            values);
                }
            }
        }


        // 更新昵称
        if (user.getNickName().size() != 0) {

            if(user.isHaveNickName()){
                ops.add(ContentProviderOperation
                        .newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                Data.RAW_CONTACT_ID + "=?" + " AND "
                                        + ContactsContract.Data.MIMETYPE + " = ?",
                                new String[] { String.valueOf(id),
                                        Nickname.CONTENT_ITEM_TYPE })
                        .withValue(Nickname.NAME, user.getNickName().get(0))
                        .build());
            }else{
                values.put(
                        android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                        id);
                values.put(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE);
                for (int i = 0; i < user.getNickName().size(); i++) {
                    values.put(Nickname.NAME, user.getNickName()
                            .get(i));
                    context.getContentResolver().insert(
                            android.provider.ContactsContract.Data.CONTENT_URI,
                            values);
                }
            }
        }
        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
                    ops);
        } catch (Exception e) {
        }
    }

}
